package org.geektimes.projects.user.validator.bean.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidAnnotationValidator implements ConstraintValidator<PasswordValid, String> {

    private final String PASSWORD_REX = "\\w{6,32}";

    private final Pattern localPattern;
    private PasswordValid annotation;

    public PasswordValidAnnotationValidator() {
        this.localPattern = Pattern.compile(PASSWORD_REX);
    }

    @Override
    public void initialize(PasswordValid annotation) {
        this.annotation = annotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.length() == 0) {
            return false;
        }

        if(matchPart(value, localPattern)) {
            return true;
        } else {
            context.disableDefaultConstraintViolation();//禁用默认的message的值
            //重新添加错误提示语句
            context.buildConstraintViolationWithTemplate(annotation.message()).addConstraintViolation();
            return false;
        }
    }

    private boolean matchPart(String part, Pattern pattern) {

        Matcher matcher = pattern.matcher(part);
        return matcher.matches();
    }
}
